import numpy as np
import cv2
import cvutil
import dual_matrix_transform as dmt
import global_settings as R

center_point = cvutil.get_center_point()
cv2.namedWindow('result image window')
drawing = False
pt1_x, pt1_y = None, None


def get_paint_color():
    if isinstance(R.paintColor, tuple):
        return R.paintColor
    elif isinstance(R.paintColor, type(get_paint_color)) or isinstance(R.paintColor, type(lambda: None)):
        return R.paintColor()
    else:
        raise Exception('画笔参数设置错误,应为 BGRA 元组或生成画笔颜色的方法')


def draw(event, x, y, flags, param):
    global pt1_x, pt1_y, drawing
    if event == cv2.EVENT_LBUTTONDOWN:
        drawing = True
        pt1_x, pt1_y = x, y
    elif event == cv2.EVENT_MOUSEMOVE:
        if drawing:
            cv2.line(paint_mat, (pt1_x, pt1_y), (x, y), color=get_paint_color(), thickness=R.paintThickness)
            for i in range(R.axisNum):
                new_line = dmt.rotateLine(((pt1_x, pt1_y), (x, y)), np.pi / R.axisNum * i * 2, center_point)
                new_line = new_line.astype(int)
                cv2.line(paint_mat, new_line[0], new_line[1], color=get_paint_color(), thickness=R.paintThickness)
            pt1_x, pt1_y = x, y
    elif event == cv2.EVENT_LBUTTONUP:
        drawing = False
        cv2.line(paint_mat, (pt1_x, pt1_y), (x, y), color=get_paint_color(), thickness=R.paintThickness)


cv2.setMouseCallback("result image window", draw)

axis_mat = cvutil.get_axis_mat()
paint_mat = cvutil.get_blank_mat()

while True:
    show_mat = None
    if R.displayAxis:
        show_mat = cvutil.merge_mat(paint_mat, axis_mat)
    else:
        show_mat = paint_mat
    cvutil.imshow("result image window", show_mat)
    if cv2.waitKey(20) == 27:
        break

cv2.imwrite(cv2.imwrite(R.saved_file_name, paint_mat, [cv2.IMWRITE_PNG_COMPRESSION, R.compress_level]))
cv2.destroyAllWindows()
